<template>
  <div>
    <el-descriptions title="唯一标识：">
      <el-descriptions-item label="创建人：">{{detailInfo?.cme_create_by|| '-'}}</el-descriptions-item>
      <el-descriptions-item label="创建日期：">{{detailInfo?.cme_create_date|| '-'}}</el-descriptions-item>
      <el-descriptions-item label="模型名称：">{{detailInfo?.cme_name|| '-'}}</el-descriptions-item>
      <el-descriptions-item label="模型图标：">
        <div style="display: inline-block;"><img :src="'./cmdb/'+detailInfo.cme_icon+'.svg'" alt="" style="width: 40px;height: 40px;" /></div>
      </el-descriptions-item>

      <el-descriptions-item label="所属分组：">{{detailInfo?.cmc_name|| '-'}}</el-descriptions-item>
      <el-descriptions-item label="模型类型：">{{detailInfo?.cme_type==1?'软件类型':detailInfo?.cme_type==2?'硬件类型' :'' || '-'}}</el-descriptions-item>
    </el-descriptions>
    <el-card>
      <div class="top-search" v-has-permi="['cmdb:property:query']">
        <el-form :model="searchConfig" label-width="auto" :inline="true">
          <template v-for="(topItem, topIindex) in searchFormList" :key="topIindex">
            <el-form-item :label="topItem.cmc_k_name" v-if="topIindex<=1 &&!unfoldFlag && topItem.isShow ">
              <div class="df">
                <el-input v-model="topItem.searchValue" placeholder="请输入" @keydown.enter="searchList"> </el-input>
              </div>
            </el-form-item>
            <el-form-item :label="topItem.cmc_k_name" v-if="unfoldFlag && topItem.isShow ">
              <div class="df">
                <el-input v-model="topItem.searchValue" placeholder="请输入" @keydown.enter="searchList"> </el-input>
              </div>
            </el-form-item>
          </template>
          <el-form-item label="">
            <el-button type="primary" @click="searchList">查询</el-button>
            <el-button plain @click="resertList">重置</el-button>
            <el-button @click="unfoldForm" plain>
              {{ !unfoldFlag ? '展开' : '收起' }}
              <el-icon class="el-icon--right">
                <ArrowDown v-if="!unfoldFlag" />
                <ArrowUp v-else />
              </el-icon>
            </el-button>
          </el-form-item>

          <!-- <el-form-item v-if="unfoldFlag" label="vlanID">
            <el-input v-model="searchConfig.policeName" placeholder="请输入"> </el-input>
          </el-form-item>
          <el-form-item v-if="unfoldFlag" label="CIDR">
            <el-input v-model="searchConfig.policeRuleId" placeholder="请输入"> </el-input>
          </el-form-item>

          <el-form-item v-if="unfoldFlag" label="创建时间">
            <el-date-picker v-model="searchConfig.vlanTime" type="daterange" range-separator="到" start-placeholder="开始时间" end-placeholder="结束时间" />
          </el-form-item>

          <el-form-item v-if="unfoldFlag" label="创建人">
            <el-select v-model="searchConfig.vlanCreator" placeholder="请选择">
              <el-option label="111" value="1" />
              <el-option label="dragon" value="0" />
            </el-select>
          </el-form-item>

          <el-form-item label="">
            <el-button type="primary">查询</el-button>
            <el-button plain>重置</el-button>
            <el-button @click="unfoldForm" plain>
              {{ !unfoldFlag ? '展开' : '收起' }}
              <el-icon class="el-icon--right">
                <ArrowDown v-if="!unfoldFlag" />
                <ArrowUp v-else />
              </el-icon>
            </el-button>
          </el-form-item> -->
        </el-form>
      </div>
      <div class="table-top">
        <el-button v-has-permi="['cmdb:property:add']" type="primary" @click="addTable">增加</el-button>
        <el-button v-has-permi="['cmdb:property:edit']" type="success" @click="handlerEdit">编辑</el-button>
        <el-button v-has-permi="['cmdb:property:delete']" type="danger" @click="handleDel">删除</el-button>
        <!-- <el-button plain>导出</el-button> -->
      </div>
      <div class="table-content">
        <el-table ref="multipleTableRef" :data="detailList" style="width: 100%;" @selection-change="handleSelectionChange">
          <el-table-column v-if="detailList&&detailList.length" type="selection" width="55" />

          <el-table-column :property="item.cmc_k_key" :label="item.cmc_k_name" show-overflow-tooltip v-for="(item, index) in KeylList" :key="index">
            <template #default="scope">
              <!-- 处理下拉 -->
              <span v-if="scope.row['select_arr'+item.cmc_k_key]">{{ filterSelect(scope.row['select_arr'+item.cmc_k_key],scope.row[item.cmc_k_key])}} </span>

              <div v-if=" item.cmc_k_type==4">
                <el-switch @change="changeMonitoring(scope.row,item)" v-model="scope.row[item.cmc_k_key]" inline-prompt active-text="开启" inactive-text="关闭" />
              </div>
              <div v-if="item.cmc_k_type!=4 && item.cmc_k_type!=3">
                {{  scope.row[item.cmc_k_key]}}
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column :property="item.value" :label="item.name" show-overflow-tooltip v-for="(item, index) in labelList" :key="index">
            <template #default="scope">
              <span v-if="scope.row[item.value+'select']">{{ filterSelect(scope.row[item.value+'select'],scope.row[item.value])}} </span>
            </template>
          </el-table-column> -->

          <!-- <el-table-column v-if="detailList&&detailList.length" property="" width="150" label="是否监控" fixed="right">
            <template #default="scope"> <el-switch @change="changeMonitoring(scope.row)" v-model="scope.row.isMonitoring" inline-prompt active-text="监控" inactive-text="不监控" /> </template>
          </el-table-column>
          <el-table-column v-if="detailList&&detailList.length" property="" width="150" label="是否覆盖" fixed="right">
            <template #default="scope"> <el-switch @change="changeStatus(scope.row)" v-model="scope.row.status" inline-prompt active-text="覆盖" inactive-text="不覆盖" /> </template>
          </el-table-column>
          <el-table-column v-if="detailList&&detailList.length" property="" width="150" label="是否开机自启" fixed="right">
            <template #default="scope"> <el-switch @change="changeStatus(scope.row)" v-model="scope.row.powerBoot" inline-prompt active-text="自启" inactive-text="不自启" /> </template>
          </el-table-column> -->

          <!-- <el-table-column v-if="detailList&&detailList.length" property="name" width="150" label="操作" fixed="right">
            <template #default="scope"> <el-button type="danger" @click="handleDel(scope.row)" size="small">删除</el-button> </template>
          </el-table-column> -->
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getDetailList" />
      </div>
    </el-card>

    <el-drawer v-model="drawerAdd" size="60%" direction="rtl" :title="drawerAddTitle">
      <template #default>
        <!-- <el-form :model="addFrom" label-width="auto" class="custom-form">
          <el-form-item label="唯一标识" prop="cmc_k_value"   :rules="getRules(item)">
            <el-input   v-model="addFrom.cmc_k_value" placeholder="请输入"> </el-input> 
          </el-form-item>
        </el-form> -->

        <el-form :model="{}" label-width="auto" class="custom-form">
          <template v-for="(item, index) in KeylList" :key="item.cmc_k_key">
            <div v-if="item.cmc_k_key=='isMonitoring'"></div>

            <el-form-item v-else-if="item.cmc_k_key == 'ip'" :label="item.cmc_k_name" :prop="item.cmc_k_value" :rules="[{ validator: getRules(item), trigger: 'blur' }]">
              <el-tree-select :props="{label:'key'}" v-model="item.cmc_k_value" :data="IPTreeList" :node-key="'key'" :render-after-expand="false" style="width: 100%" />
            </el-form-item>

            <el-form-item :label="item.cmc_k_name" :prop="item.cmc_k_value" :rules="getRules(item)" v-else>
              <!-- {{ item.cmc_k_type }} ::{{  item.cmc_k_value}} -->
              <el-input v-if="item.cmc_k_type == 0" v-model="item.cmc_k_value" placeholder="请输入"> </el-input>
              <el-input v-if="item.cmc_k_type == 1" v-model="item.cmc_k_value" placeholder="请输入" type="textarea"> </el-input>
              <el-date-picker v-if="item.cmc_k_type == 2" v-model="item.cmc_k_value" placeholder="请选择" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width:100%;" />
              <el-select v-if="item.cmc_k_type == 3" v-model="item.cmc_k_value" placeholder="请选择">
                <el-option v-for="sele in item.cmc_k_select_list" :key="sele.id" :label="sele.key" :value="sele.value" />
              </el-select>
              <el-switch v-if="item.cmc_k_type == 4" v-model="item.cmc_k_value" inline-prompt active-text="是" inactive-text="否"     />
            </el-form-item>
          </template>
        </el-form>
        <!-- <el-form :model="item" label-width="auto" v-for="(item, index) in KeylList" :key="item.cmc_k_key">
            <el-form-item :label="item.cmc_k_name" :prop="item.cmc_k_value" :rules="[{ validator: getRules, trigger: 'blur' }]">
              <el-input v-model="item.cmc_k_value" placeholder="请输入"> </el-input>
            </el-form-item>
        </el-form> -->
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawerAdd=false">取消</el-button>
          <el-button type="primary" @click="addEnter">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { propertyDetailList, propertyKeylList, propertyDetailAdd ,propertyDetailEdit,propertyDetailDel ,serviceIsMonitoring ,modelDetailList ,freeIpListTree} from '@/api/cmdb/model'
import {Plus} from '@element-plus/icons-vue'
const props = defineProps(['cme_key','model_id'])
/* -------------------------------------------------------------------------------上方查询start */
const unfoldFlag = ref(false)
const searchConfig = ref({
  vlanName: '',
  vlanGateway: '',
  policeName: '',
  policeRuleId: '',
  vlanTime: '',
  vlanCreator: '',
});
const unfoldForm = () => {
  unfoldFlag.value = !unfoldFlag.value
}
/* --------------------------------------------------------------------------上方查询end */

const data = reactive({

  cme_key: "",
  drawerAdd: false,
  drawerAddTitle: "",
  addFrom: {},
  total: 0,
  rowID:''

})
const {  cme_key, drawerAdd, drawerAddTitle, addFrom, total,rowID } = toRefs(data)

const getRules = (item) => {
  // console.log(item);

  return [{
    required: item.cmc_k_setting,
    validator: (rule, value, cb) => {

      // console.log(rule);

      if (!rule.field) {
        cb(new Error('必填!'));
      } else {
        cb();
      }
    }, trigger: 'blur'
  }]

  // return [{ required: item.cmc_k_setting, message: `请输入`,trigger: 'blur' }]
}
const filterSelect = (item,value)=>{
  console.log(item,value);

  let res = '-'
    if(item&&item.length){
      item.forEach(element => {
          if(element.value==value){
            res = element.key
          }
      });
    }

    return res

}
const multipleSelection = ref([])
/* 表格选中 */
const handleSelectionChange = (val: any) => {
  console.log(val);
  multipleSelection.value = val


};
/* 修改 */
const handlerEdit = async()=>{
  console.log(multipleSelection.value);
  console.log(KeylList.value);

  if(multipleSelection.value&&multipleSelection.value.length!==1){
    ElMessage.error('请选择一条数据')
    return false
  }
  await getIPTreeList()

  drawerAdd.value = true
  drawerAddTitle.value = '修改模型资产'

  let data2:any = multipleSelection.value[0]
  KeylList.value.forEach(element => {
    let key =  element.cmc_k_key
    console.log(data2.hasOwnProperty(key));
      if(data2.hasOwnProperty(key)){
        element['cmc_k_value'] = data2[key]
      }
  });

  console.log(KeylList.value);

  // let keysObj = []
  // for (const ele in  multipleSelection.value[0]){
  //     console.log(ele);
  //     console.log();
  //     keysObj.push({
  //      [ 'cmc_k_'+ele.split([multipleSelection.value[0].cme_key])[1]] :multipleSelection.value[0][ele]
  //     })

  //  }
  //  console.log(keysObj);


  // KeylList.value = multipleSelection.value[0]
  rowID.value =  multipleSelection.value[0]._id


}



/* del */
const handleDel = async(row)=>{
  if(multipleSelection.value&&multipleSelection.value.length===0){
    ElMessage.error('请至少选择一条数据')
    return false
  }



ElMessageBox.confirm(
  '确认要删除吗',
  '提示',
  {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }
)
  .then(async() => {

    const arr = multipleSelection.value.map((item:any)=>item._id)
      console.log(arr);
    const res= await propertyDetailDel(arr)
    console.log(res);
    if(res.data){

    ElMessage({
      type: 'success',
      message: '删除成功',
    })

    
    }
    await getDetailList()

  })
  .catch(() => {

  })
}

/* 是否监控 */
const changeMonitoring = async(row,item)=>{
  console.log(row,item);
  // list: KeylList.value, cme_key: cme_key.value ,_id:rowID.value


console.log(detailInfo.value);



let data = {   cme_key: cme_key.value ,_id:row._id ,isMonitoring:row['isMonitoring'] || false ,serviceType:detailInfo.value.serviceType,cme_port:detailInfo.value.cme_port ,
  cmc_key:detailInfo.value.cmc_key ,status:row['status']|| false, powerBoot:row['powerBoot']|| false ,cme_type:detailInfo.value.cme_type,
  root:row.root,password:row.password,ip:row.ip
}



try{
  const res= await serviceIsMonitoring(data)
  console.log(res);

  if(res.data){
    ElMessage.success(row.isMonitoring?'开启成功':'关闭成功')

  }
  await getDetailList()

}catch(err){
  console.log(err);
  await getDetailList()
}




//  const res = await propertyDetailEdit({ list: row.list, cme_key: cme_key.value ,_id:row._id ,isMonitoring:row.isMonitoring})
//     console.log(res);



//     if(res.data){
//       ElMessage.success(row.isMonitoring?'开启成功':'关闭成功')
//     }


}
/* 是否覆盖 开机自启 */
const changeStatus  = async(row)=>{
 const res = await propertyDetailEdit({ list: row.list, cme_key: cme_key.value ,_id:row._id ,isMonitoring:row.isMonitoring ,status:row.status|| false, powerBoot:row.powerBoot|| false})
    console.log(res);

    if(res.data){
      ElMessage.success(row.isMonitoring?'操作成功':'操作成功')
      await getDetailList()
    }

}



/*添加 */
const addTable = async() => {
  drawerAdd.value = true
  drawerAddTitle.value = '添加模型资产'
  console.log(KeylList.value);
  await getIPTreeList()

  KeylList.value.forEach(element => {

    if(element.cmc_k_type==4){
      element['cmc_k_value'] = null
    }else{
      element['cmc_k_value'] = ''
    }
  });

  console.log(KeylList.value);

}
/* 确认添加 */
const addEnter = async () => {
  console.log(addFrom.value);
  console.log(KeylList.value);

  let isFinish = true
  KeylList.value.forEach(element => {
    if (element.cmc_k_setting && element.cmc_k_value==='') {
      isFinish = false
    }  
  });
  if (!isFinish) {
    ElMessage.error(`请检查必填项是否填写完整`)
    return false
  }

  let data = { list: KeylList.value, cme_key: cme_key.value }
  console.log(data);

  let arr :any= {}
  KeylList.value.forEach(element => {
    // arr[cme_key.value+ element.cmc_k_key]=element.cmc_k_value
    // if(element.cmc_k_select_list&&element.cmc_k_select_list.length){ // 处理下拉
    //   arr[cme_key.value+'select_arr'+ element.cmc_k_key]=element.cmc_k_select_list
    // }
    arr[element.cmc_k_key]=element.cmc_k_value
    if(element.cmc_k_select_list&&element.cmc_k_select_list.length){ // 处理下拉
      arr['select_arr'+ element.cmc_k_key]=element.cmc_k_select_list
    }
  });


  arr['ip'] = [arr['ip']]



  console.log(arr);



// return false
 



  // const res =   drawerAddTitle.value == '添加模型资产'? await propertyDetailAdd({ list: KeylList.value, cme_key: cme_key.value }) : await propertyDetailEdit({ list: KeylList.value, cme_key: cme_key.value ,_id:rowID.value})
  const res =   drawerAddTitle.value == '添加模型资产'? await propertyDetailAdd({ ...arr, cme_key: cme_key.value }) : await propertyDetailEdit({ ...arr, cme_key: cme_key.value ,_id:rowID.value})
  console.log(res);

  if (res.data) {
    ElMessage.success(drawerAddTitle.value +'成功')
    drawerAdd.value = false
    await getDetailList()
    await getKeyList()
    await getIPTreeList()
  }



}




/* 获取ip树形接口 */
const IPTreeList = ref([])
const getIPTreeList =async ()=>{
  const res= await freeIpListTree()
  console.log(res);
  IPTreeList.value = res.data

}



const detailInfo = ref<any>([])
/* 获取模型的详情 */
const getModelDetail = async()=>{
  const res = await modelDetailList(props.model_id)
  console.log(res);
  detailInfo.value = res.data
}


const KeylList = ref<any>()
const searchSelect = ref<any>()
const searchFormList = ref<any>([])
const getKeyList = async () => {

  const res = await propertyKeylList(cme_key.value)
  console.log(res);
  KeylList.value = res.data
  searchSelect.value =res.data
   res.data.forEach(item=>{
    item['isUse']=false
    if(item.cmc_k_key=='password' || item.cmc_k_key=='isMonitoring'|| item.cmc_k_key=='powerBoot'|| item.cmc_k_key=='status'){
      item.isShow= false
    }else{
      item.isShow= true
    }
  })
  searchFormList.value = [...res.data]
  console.log(searchFormList.value);
  console.log(searchSelect.value);

}


const searchList  = async()=>{
  console.log(searchFormList.value);

  queryParams.value.queryList = []

  searchFormList.value.forEach((element:any) => {
    if(element.searchValue){
      console.log(element);
     queryParams.value.queryList.push({
        key:  element.cmc_k_key,
        value:element.searchValue,
        type:element.cmc_k_type,
      })
    }
  });
  console.log(queryParams.value);

  await getDetailList()

}

/* 重置 */
const resertList = async()=>{
  queryParams.value.queryList = undefined

  searchFormList.value.forEach(element => {
    element.searchValue =''
  });

  await getDetailList()

}







const queryParams=ref<any>( {
    pageNum: 1,
    pageSize: 10,
    queryList:undefined
  })



const detailList = ref<any>()
const labelList = ref<any>()
const getDetailList = async () => {
  console.log(props.cme_key);

  const res = await propertyDetailList({ ...queryParams.value, cme_key: cme_key.value })
  console.log(res);
  total.value = res.totalSize
  detailList.value = res.contentData



  labelList.value = []
  let data: any = []
  detailList.value.forEach(element => {
    if (element.list) {
      element.list.forEach((element2, index2) => {
        console.log(element2.cmc_k_name);
        /* 处理下拉选择 */
        if(element2.cmc_k_select_list){
          element['value'+index2+'select'] = element2.cmc_k_select_list
        }
        element['index' + index2] = element2.cmc_k_name
        data.push({ name: element2.cmc_k_name, value: 'value' + index2 })
        element['value' + index2] = element2.cmc_k_value
      });
    }
  });
  console.log(detailList.value);
  // console.log(JSON.stringify(data));


  // 使用reduce函数去除重复项
  labelList.value = data.reduce((accumulator, currentValue) => {
    // 检查累加器中是否已经有具有相同name的对象
    const existingItem = accumulator.find(item => item.name === currentValue.name);

    // 如果没有找到重复项，则将当前值添加到累加器中
    if (!existingItem) {
      accumulator.push(currentValue);
    }

    // 无论是否添加，都返回累加器以用于下一次迭代
    return accumulator;
  }, []); // 初始累加器为空数组

  console.log(labelList.value);



}
watchEffect(async () => {
  cme_key.value = props.cme_key
  if (props.cme_key) {
    await getKeyList()
    await getDetailList()
    await getModelDetail()
    await getIPTreeList()

  }

});


defineExpose({
  getDetailList
})
</script>

<style scoped lang="scss">
.table-content{
  margin-top: 20px;
}
.custom-form {
  .el-input {
    width: 100%;
  }

  .el-select {
    width: 100%;
  }

  :deep(.el-input__wrapper) {
    width: 100%;
  }
}
</style>
